
//代码清单9-3  注册监听
//代码清单 9-6
#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import "FlutterIosTextLabelFactory.h"
@implementation AppDelegate{
    FlutterMethodChannel* methodChannel;
    FlutterBasicMessageChannel* messageChannel;
    FlutterEventSink mEventSink;
    NSTimer* nsTime;

}


- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   [GeneratedPluginRegistrant registerWithRegistry:self];

    //FlutterMethodChannel 与 Flutter 之间的双向通信
    [self  methodChannelFunction];
    [self  registerEventChannerl];
    [FlutterIosTextLabelFactory registerWithRegistrar:[self registrarForPlugin:@"FlutterIosTextLabelPlugin"]];

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

-(void) methodChannelFunction{
    //获取当前的 ViewControlle
    FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
    //创建 FlutterMethodChannel
    // flutter_and_native_101 是通信标识
    methodChannel = [FlutterMethodChannel
                     methodChannelWithName:@"flutter_and_native_101"
                     binaryMessenger:controller.binaryMessenger];

    __weak typeof(self) weakSelf = self;

    //设置监听
    [methodChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
        // Flutter传过来的方法名称
        NSString *method=call.method;
        // Flutter传过来的参数
        NSDictionary * arguments = call.arguments;

        [weakSelf methodCallMethod:method andWithArguments:arguments andWithResult:result];
    }];
}

//消息方法处理
-(void)methodCallMethod: (NSString*) method andWithArguments:(NSDictionary * ) arguments andWithResult: (FlutterResult) result{

    if ([method isEqualToString:@"test"]) {

        NSLog(@"flutter 调用到了 ios test");
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:@"ABC" forKey:@"message"];
        [dic setObject: [NSNumber numberWithInt:200] forKey:@"code"];
        //FlutterResult回调 发消息至 Flutter 中
        //此方法只能调用一次
        result(dic);
        //代码清单9-3-1  发送消息至Flutter中
        NSMutableDictionary *dics = [NSMutableDictionary dictionary];
        [dics setObject:@" 原生中数据" forKey:@"message"];
        [dics setObject: [NSNumber numberWithInt:200] forKey:@"code"];
                
        //通过此方法 可以主动向Flutter中发送消息
        //可以多次调用
        [methodChannel invokeMethod:@"test" arguments:dics];


    }
}

//------------------------------------------------------------------------------------------------
//代码清单 9-6-1
-(void) basicMessageChannelFunction{
    //获取当前的 controller
    FlutterViewController * controller
            = (FlutterViewController*)self.window.rootViewController;
    // 初始化定义
    // flutter_and_native_100 j
    messageChannel = [FlutterBasicMessageChannel
                      messageChannelWithName:@"flutter_and_native_100"
                      binaryMessenger:controller.binaryMessenger];
    
     __weak typeof(self) weakSelf = self;
    // 接收消息监听
    [messageChannel setMessageHandler:^(id message, FlutterReply callback) {
        //处理消息
        [weakSelf basicMessageChannelCall:message andWithReply:callback];
    }];
}
//代码清单 9-6-2 消息处理
-(void) basicMessageChannelCall:(id) message andWithReply:(FlutterReply )callback{
    NSString *method=message[@"method"];
    
    if ([method isEqualToString:@"test"]) {
        
        NSLog(@"flutter 调用到了 ios test");

        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:@"ios 回调消息" forKey:@"message"];
        [dic setObject: [NSNumber numberWithInt:200] forKey:@"code"];
    
        //回调 回执消息
        callback(dic);
        
    }
}
//代码清单 9-6-3
///iOS中通过 BasicMessageChannel 通道向Flutter中发送消息
-(void)baseMessageSendFunction{

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"这里是数据" forKey:@"message"];
    [dic setObject: [NSNumber numberWithInt:200] forKey:@"code"];
    
    //通过这个方法 iOS可以主动多次 向 Flutter 发送消息
    [messageChannel sendMessage:dic];
    
}
//------------------------------------------------------------------------------------------------

//代码清单9-9-1 注册
//EventChannel 通信
-(void)registerEventChannerl{
    //获取当前的 controller
    FlutterViewController* controller =
            (FlutterViewController*)self.window.rootViewController;
    //创建 EventChannel 通信
    FlutterEventChannel * eventChannel=[FlutterEventChannel
                                        eventChannelWithName:@"flutter_and_native_103"
                                        binaryMessenger:controller.binaryMessenger];
    //添加监听
    [eventChannel setStreamHandler:self];
}

//EventChannel 注册成功回调方法
#pragma mark - FlutterStreamHandler
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
                                       eventSink:(FlutterEventSink)eventSink{
    mEventSink = eventSink;
     NSLog(@"EventChannle 注册");
    //开启定时
    [self startTimer];
    return nil;
}

//EventChannel 取消回调方法
 #pragma mark - FlutterStreamHandler
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
    NSLog(@"EventChannle 取消");
    mEventSink= nil;
    [self stopTimer];
    return nil;
}

//代码清单9-9-2 模拟消息发送
// 启动定时器
-(void)startTimer{
    //NSTime的类方法创建一个定时器并且启动这个定时器
    //p1:每个多长时间调用定时器函数，以秒为单位
    //p2:表示实现这个定时器函数的对象
    //p3:定时器函数对象
    //p4:可以传入定时器函数中一个参数，无参数传入nil
    //p5:定时器是否重复操作YES表示重复，NO表示只完成一次函数调用
    nsTime = [NSTimer scheduledTimerWithTimeInterval:1
                      target:self selector:@selector(updateTime:)
                                            userInfo:nil repeats:YES];
}

-(void)updateTime:(NSTimer*) timer{
    NSLog(@"参数为：%@",timer.userInfo);
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式

       NSString *timeSp = [NSString stringWithFormat:@"%ld",
                           (long)[datenow timeIntervalSince1970]];

    if(mEventSink!=nil){
        mEventSink([NSString stringWithFormat:@"定时执行 %@",timeSp]);
    }
}

// 停止定时器
-(void)stopTimer{
    [nsTime invalidate];
}

@end
